<!-- 正文开始 -->
<div class="layui-fluid" id="foodMenu">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar" lay-filter="foodMenu">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">类型</label>
                        <div class="layui-input-inline">
                            <select name="type" lay-verify="required" lay-filter="foodMenu-type">
                                <option value="" data-default=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                            <input name="name" class="layui-input" type="text">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn icon-btn btnSearch"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button class="layui-btn btnAdd" ><i class="layui-icon layui-icon-add-1"></i>增加</button>
                    </div>
                </div>
            </div>
            <div class="foodMenuTableWrapper">
                <table class="layui-table" id="foodMenuTable" lay-filter="foodMenuTable"></table>
            </div>

        </div>
    </div>
    <!-- 表格操作列 -->
    <script type="text/html" class="tpl-foodMenuTable-operator">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-xs btn-upload" data-id="{{d.id}}" lay-event="up">上传图片</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <!-- 表格状态列 -->
    <script type="text/html" class="tpl-foodMenuTable-status">
        <input type="checkbox" lay-filter="tpl-foodMenuTable-status" value="{{d.status}}" data-id="{{d.id}}" lay-skin="switch" lay-text="售中|售完"
               {{d.status==1?'checked':''}}/>
    </script>

</div>

<style>
    #foodMenu .layui-table-body .layui-table-cell{
        height: 100px !important;
        white-space: normal;
    }
    #foodMenu .layui-table-body .layui-table-cell .layui-btn{
        width: 60px;
        height: 30px;
        margin-top: 5px;
        vertical-align: middle;
        padding-top: 5px;
    }
</style>


<script>
    layui.use(['layer', 'table', 'form', 'http', 'upload','tools'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var form = layui.form;
        var http = layui.http;
        var tools = layui.tools;
        var upload = layui.upload;

        var $view = $("#foodMenu");
        var $tbView = $view.find(".foodMenuTableWrapper");
        var foodMenuTableIns;
        var foodTypeList;
        var rowIndex,rowId;
        var orderByClause = "name";

        var fnGetTypeName = function(d){
          if(typeof d.type === 'undefined' || !foodTypeList){
              return d.type;
          }
          for(var i=0;i<foodTypeList.length;i++){
              var item = foodTypeList[i];
              if(item.code == d.type){
                  return item.name;
              }
          }
          return d.type;
        };

        var fnImgTemplet = function(d){
          if(d.imgUrl){
              return '<img src="' + d.imgUrl + '" height="100%">';
          }else{
              return '';
          }
        };

        tools.select.codes('FoodType',$view.find("select[name='type']"),function (res) {
            if(res.ok){
                foodTypeList = res.data;
                form.render('select','foodMenu');
                foodMenuTableIns = fnRender();
            }
        });

        var fnGetSearchParam = function(){
            var params = {
                orderByClause: orderByClause,
                type: $view.find("select[name='type']").val(),
                name: $view.find("input[name='name']").val()
            };
            return params;
        };

        var fnRender = function() {
            return table.render({
                id: 'foodMenuTable',
                elem: '#foodMenuTable',
                method: 'post',
                contentType: "application/json",
                url: http.base_server + 'foodMenu/list',
                where: fnGetSearchParam(),
                page: true,
                cellMinWidth: 50,
                hide: true,
                height: 'full-200',
                limits : [10,20,30,40,50],
                limit : 20,
                autoSort: false,
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                cols: [[
                    {type: 'numbers'},
                    {field: 'id', title: 'ID', width: 50, hide: true},
                    {field: 'type', sort: true, title: '类型',templet: fnGetTypeName,width:100},
                    {field: 'name', sort: true, title: '名称', width: 150},
                    {field: 'price', sort: true, title: '价格', width: 60},
                    {field: 'introduce', sort: true, title: '简介', width: 250},
                    {
                        field: 'status',
                        sort: true,
                        title: '状态',
                        templet: $view.find('.tpl-foodMenuTable-status'),
                        width: 80
                    },
                    {field: 'img', sort: false, title: '图片', width: 140, templet: fnImgTemplet},
                    {align: 'center', title: '操作', width: 230, toolbar: $view.find('.tpl-foodMenuTable-operator')},
                    {field: 'updateTime', sort: true, title: '更新时间',width:150}
                ]],
                error: function (code, msg) {
                    http.fail(code, msg);
                },
                done: function () {
                    fnRenderUpload();
                }
            });
        };

        // 修改foodMenu状态
        form.on('switch(tpl-foodMenuTable-status)', function (obj) {
            http.post('foodMenu/update', {
                id: $(obj.elem).attr("data-id"),
                status: obj.elem.checked ? 1 : 0
            }, function (res) {
                if (res.ok) {
                    layer.msg(res.msg, {icon: 1});
                    var field = obj.othis.parents("td:eq(0)").attr("data-field");
                    var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
                    foodMenuTableIns.getCache()[idx][field]=obj.elem.checked ? 1 : 0;
                } else {
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    foodMenuTableIns.renderForm('checkbox');
                }
            });
        });

        var fnRenderUpload = function(){
            $tbView.find(".layui-table-body .layui-table-cell .btn-upload").click(function(){
                rowIndex = $(this).parents("tr:eq(0)").attr("data-index");
                rowId = $(this).attr("data-id");
            });
            upload.render({
                elem: $tbView.find(".layui-table-body .layui-table-cell .btn-upload")
                , url: http.base_server + 'foodMenu/upload/'
                //,auto: false
                , accept: 'file' //普通文件
                //,multiple: true
                //,bindAction: $view.find("button[data-id='btnDoUpload']") //选完文件后不自动上传
                , data: function () {
                    return {id: rowId}
                } //必须是函数
                , exts: 'jpg|png'
                , before: function (obj) {
                    if(typeof rowId === 'undefined'){
                        http.failMsg("RowID不存");
                        return false;
                    }

                    layer.load(2); //上传loading
                    return true;
                }
                , done: function (res) {
                    layer.closeAll('loading'); //关闭loading
                    if (http.ok(res.code)) {
                        $tbView.find('.layui-table-body tr[data-index="'+rowIndex+'"]')
                            .find('td[data-field="img"] div').html('<img src="' + res.data + '" height="100%">');
                        http.okMsg("上传成功");
                    } else {
                        http.fail(res);
                    }
                },
                error: function (index, upload, status, msg) {
                    layer.closeAll('loading'); //关闭loading
                    http.fail(status, msg);
                }
            });
        };

        table.on('tool(foodMenuTable)', function (rowObj) {
            var data = rowObj.data;
            var layEvent = rowObj.event;

            if (layEvent === 'del') { // 删除
                layer.confirm("确定删除该行?",{btn:["确定","取消"]},
                    function(index,obj) {
                        layer.closeAll('dialog');
                        http.post('foodMenu/delete', {id: data.id}, function (res) {
                            if (res.ok) {
                                rowObj.del();
                            }
                        })
                    }
                );
                return;
            }
            if (layEvent === 'edit') { // 修改
                var param = tools.param = {};
                param.tableIns = foodMenuTableIns;
                param.foodTypeList = foodTypeList;
                param.fnSearch = fnSearch;
                param.data = data;
                param.rowObj = rowObj;
                param.rowIndex = rowObj.tr.attr("data-index");

                showEditModel(false);
                return;
            }
        });

        var fnSearch = function(){
            var params = fnGetSearchParam();
            foodMenuTableIns.reload({where:params,page: {curr: 1}});
        };

        $view.find(".btnSearch").click(function(){
            fnSearch();
        });
        form.on("select(foodMenu-type)",function(data){
            fnSearch();
        });
        table.on("sort(foodMenuTable)",function(obj){
            orderByClause = (obj.field || '')+ ' ' + (obj.type || '');
            fnSearch();
        });

        // 显示表单弹窗
        function showEditModel(isAdd) {
            tools.open({
                area: ['800px','500px'],
                title: isAdd ? '添加': '修改',
                url: http.viewPath + '/system/foodMenuForm.html?v=1',
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');  // 禁止出现滚动条
                }
            });
        };

        $view.find(".btnAdd").click(function () {
            var param = tools.param = {};
            param.tableIns = foodMenuTableIns;
            param.foodTypeList = foodTypeList;
            param.fnSearch = fnSearch;
            param.data = {
                type:2,
                status:1
            };
            showEditModel(true);
        });


    });
</script>